import store from '@/store'

export function getProvider(service) {
	return new Promise((reslove, reject) => {
		uni.getProvider({
			service,
			success(res) {
				reslove(res)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

export function payment(data, payType, apiPayTypeVal) {
	
	return new Promise(async (reslove, reject) => {
		// #ifdef APP-PLUS
		// 支付订单号
		if (!data.balance_order_num) {
			data.balance_order_num = (data.order_no || data.order_num || data.send_platform_order_num || data.send_order_num)
		}
		
		if (payType === 'alipay_method' || payType === 'wxapp') {
			let provPara = '';
			let ordInfo = '';
			
			if(payType === 'alipay_method') {
				ordInfo = data.pay_config.pay_url;
				provPara = 'alipay';
			}
			
			if(payType === 'wxapp') {
				ordInfo = data.pay_config;
				provPara = 'wxpay';
			}
			
			uni.requestPayment({
				provider: provPara,
				orderInfo: ordInfo,
				success(res) {
					reslove(res)
				},
				fail(err) {
					uni.showToast({
						title: '亲，取消支付了',
						icon: 'error'
					})
					reject(err)
				},
			})
			
		}
		
		if (payType === 'adapay_alipay') {
			let href_url = data.pay_config;
			
			await plus.runtime.openURL(href_url, err => {
				uni.showToast({
					title: "打开支付宝失败！请检查是否已安装？" + JSON.stringify(err),
					// title: err,
					icon: 'none'
				})
				reject()
			}, 'com.eg.android.AlipayGphone');
		
			return reslove();
		}
		// #endif

		if (['wxpay', 'mbpay_wxmini'].indexOf(payType) !== -1) {
			// #ifndef APP-PLUS
			const provParam = await getProvider('payment');
			uni.requestPayment({
				provider: provParam,
				...data.pay_config,
				success(res){
					reslove(res)
				},
				fail(err){
					if (err.errMsg && (
					err.errMsg.indexOf('jsapi has been banned') !== -1
					|| err.errMsg.indexOf('access denied') !== -1
					) && !store.getters.showAppQrcodePopup) {
						store.commit('APP_QRCODE_SET_FUN', true)
						store.commit('WXPAY_TIP_SET_FUN', '微信支付功能暂无法使用，请下载APP进行操作')
					}else{
						uni.showToast({
							title: '亲，取消支付了',
							icon: 'error'
						})
					}
					reject(err)
				},
			})
			// #endif
		}
		
		if (payType === 'adapay_mini') {
			// #ifdef APP-PLUS
			// APP跳转小程序
			await store.commit('LAUNCH_MP_SET_FUN', {
				type: data.pay_config.launchMPType || 0,
				appid: data.pay_config.g_id,
				path: data.pay_config.miniapp_path
			});
		
			return reslove();
			// #endif
		}
		
		if(['yeepay_wx', 'mbpay_jump_mini'].includes(payType)) {
			// #ifdef APP-PLUS
			await store.commit('LAUNCH_MP_SET_FUN', {
				type: data.pay_config.launchMPType || 0,
				appid: data.pay_config.miniProgramOrgId,
				path: data.pay_config.prePayTn
			});
		
			return reslove();
			// #endif
		}

	})
}
